package com.ykh.util;

import com.alibaba.fastjson.JSON;

import com.ykh.config.LogAnnotation;
import com.ykh.util.HttpContextUtils;
import com.ykh.util.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: YKH
 * Date: 2023-10-27
 * Time: 7:41
 */
@Component
@Aspect
@Slf4j
public class LogAspect {
    //标识,切点(注解加入的位置)
    @Pointcut("@annotation(com.ykh.config.LogAnnotation)")
    public void pointCut(){}

    //环绕通知 : 对方法前后都能增强
    @Around("pointCut()")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
       //日志具体功能
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = joinPoint.proceed();
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        //保存日志
        recordLog(joinPoint, time);
        return result;
    }

    private void recordLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
        log.info("=====================log start================================");
        log.info("module:{}",logAnnotation.module()); //模块名
        log.info("operation:{}",logAnnotation.operation());//操作

        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();//请求的接口名称
        String methodName = signature.getName();//请求的方法名
        log.info("request method:{}",className + "." + methodName + "()");

       //请求的参数
        Object[] args = joinPoint.getArgs();
        String params = JSON.toJSONString(args[0]);//将请求参数转变为josn格式
        log.info("params:{}",params);

        //获取request 设置IP地址
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        log.info("ip:{}", IPUtils.getIpAddr(request));


        log.info("excute time : {} ms",time);
        log.info("=====================log end================================");
    }
}
